using System;
using System.ComponentModel;
using System.Windows;

namespace MyWpfControls
{

    public enum MyTextBoxMode : uint
    {
        Normal, OnlyDigits, DigitsWithDecimal
    }

    public class WPFTextBox: System.Windows.Controls.TextBox 
    {
        [
        Bindable(true),
        Category("Data"),
        DefaultValue("Normal"),
        Description("Work mode"),
        ]
        public MyTextBoxMode InputMode
        {
            get { return (MyTextBoxMode)GetValue(InputModeProperty); }
            set { SetValue(InputModeProperty, value); }
        }
        public static readonly DependencyProperty InputModeProperty =
            DependencyProperty.Register("InputMode", typeof(MyTextBoxMode), typeof(WPFTextBox), new PropertyMetadata(MyTextBoxMode.Normal));


        public WPFTextBox()
            : base()
        {
            PreviewTextInput += WPFTextBox_PreviewTextInput;
            DataObject.AddPastingHandler(this, TextBoxPastingEventHandler);
        }

        void WPFTextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            WPFTextBox MTB = sender as WPFTextBox;
            switch (MTB.InputMode)
            {
                case MyTextBoxMode.Normal:
                    return;

                case MyTextBoxMode.OnlyDigits:
                    int dummyInt;
                    if (!Int32.TryParse(e.Text, out dummyInt))
                        e.Handled = true;
                    break;

                case MyTextBoxMode.DigitsWithDecimal:
                    double dummyDouble;
                    if (e.Text == "." & MTB.Text.IndexOf(".") == -1)
                        break;
                    if (!Double.TryParse(e.Text, out dummyDouble))
                        e.Handled = true;
                    break;
            }
        }
        private void TextBoxPastingEventHandler(object sender, DataObjectPastingEventArgs e)
        {
            WPFTextBox MTB = sender as WPFTextBox;
            if (MTB.InputMode == MyTextBoxMode.Normal)
                return;

            string clipboard = e.DataObject.GetData(typeof(string)) as string;
            switch (MTB.InputMode)
            {
                case MyTextBoxMode.OnlyDigits:
                    int dummyInt;
                    if (int.TryParse(clipboard, out dummyInt))
                        return;
                    break;
                case MyTextBoxMode.DigitsWithDecimal:
                    double dummyDouble;
                    if (double.TryParse(clipboard, out dummyDouble))
                        return;
                    break;
            }
            e.CancelCommand();
            e.Handled = true;
        }

    }
}
